package com.vieewer.btdemo.view.phonecall;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.util.Log;
import com.vieewer.btdemo.app.App;
import java.lang.reflect.Method;
import java.util.List;

public class BluetoothManager {

    private final static String DIAL_CLASS_NAME = "android.bluetooth.BluetoothHeadsetClient";  //拨打电话类名
    private final static String DIAL_METHOD_NAME = "dial";  //拨打电话方法名
    private final static String ACCEPT_CALL_METHOD_NAME = "acceptCall";  //接听电话方法名
    private final static String REJECT_CALL_METHOD_NAME = "rejectCall";  //拒接电话方法名
    private final static String TERMINATE_CALL_METHOD_NAME = "terminateCall";  //挂断电话方法名
    private final static String BLUE_TOOTH_PROFILE_FIELD = "HEADSET_CLIENT";  //蓝牙适配器远程设备类型

    private static BluetoothManager instance;
    private OnCallResultListener onCallResultListener;
    private BluetoothProfile mBluetoothProfile;
    private BluetoothDevice mDevice;

    public interface OnCallResultListener {
        //蓝牙未打开
        void onBluetoothIsClosed();

        //蓝牙未连接
        void onDeviceIsEmpty();

        //无效的电话号码
        void onPhoneIsInValid();

        void onError(String errorMsg);
    }

    public static BluetoothManager getInstance() {
        if (instance == null) {
            instance = new BluetoothManager();
        }
        return instance;
    }

    //拨打电话的实际调用
    public void dial(final String number, final OnCallResultListener onCallResultListener) {
        this.onCallResultListener = onCallResultListener;
        if (TextUtils.isEmpty(number)) {
            if (onCallResultListener != null) {
                onCallResultListener.onPhoneIsInValid();
            }
        }
        getConnectStatus(new BluetoothProfile.ServiceListener() {
            @Override
            public void onServiceConnected(int profile, BluetoothProfile proxy) {
                List<BluetoothDevice> mDevices = proxy.getConnectedDevices();
                if (mDevices != null & mDevices.size() > 0) {
                    for (BluetoothDevice device : mDevices) {
                        dial(proxy, device, number);
                        break;
                    }
                } else {
                    if (onCallResultListener != null) {
                        onCallResultListener.onDeviceIsEmpty();
                    }
                }
            }

            @Override
            public void onServiceDisconnected(int profile) {
                if (onCallResultListener != null) {
                    onCallResultListener.onDeviceIsEmpty();
                }
            }
        });
    }


    //拒接电话的实际调用 rejectCall(BluetoothDevice device)
/*
    public void rejectCall() {
        try {
            if (mBluetoothProfile == null || mDevice == null ) {
                return;
            }
            Class BluetoothHeadsetClient = Class.forName(DIAL_CLASS_NAME);
            Method methodMain = BluetoothHeadsetClient.getMethod(REJECT_CALL_METHOD_NAME, BluetoothDevice.class);
            if (methodMain != null) {
                methodMain.invoke(mBluetoothProfile, mDevice);
            }
        } catch (Exception e) {
            Log.i("yjj", "rejectCall error >>>" + e.toString());
        }
    }
*/


    public void rejectCall(final OnCallResultListener onCallResultListener) {
        this.onCallResultListener = onCallResultListener;

        getConnectStatus(new BluetoothProfile.ServiceListener() {
            @Override
            public void onServiceConnected(int profile, BluetoothProfile proxy) {
                List<BluetoothDevice> mDevices = proxy.getConnectedDevices();
                if (mDevices != null & mDevices.size() > 0) {
                    for (BluetoothDevice device : mDevices) {
                        rejectCall(proxy, device);
                        break;
                    }
                } else {
                    if (onCallResultListener != null) {
                        onCallResultListener.onDeviceIsEmpty();
                    }
                }
            }

            @Override
            public void onServiceDisconnected(int profile) {
                if (onCallResultListener != null) {
                    onCallResultListener.onDeviceIsEmpty();
                }
            }
        });
    }



    private void rejectCall(BluetoothProfile proxy, BluetoothDevice bluetoothDevice) {
        try {
            if (proxy == null || bluetoothDevice == null ) {
                return;
            }
            Class BluetoothHeadsetClient = Class.forName(DIAL_CLASS_NAME);
            Method methodMain = BluetoothHeadsetClient.getMethod(REJECT_CALL_METHOD_NAME, BluetoothDevice.class);
            if (methodMain != null) {
                methodMain.invoke(proxy, bluetoothDevice);
            }
        } catch (Exception e) {
            if (onCallResultListener != null) {
                onCallResultListener.onError(e.getMessage());
            }
        }
    }


    public void terminateCall(final OnCallResultListener onCallResultListener) {
        this.onCallResultListener = onCallResultListener;

        getConnectStatus(new BluetoothProfile.ServiceListener() {
            @Override
            public void onServiceConnected(int profile, BluetoothProfile proxy) {
                List<BluetoothDevice> mDevices = proxy.getConnectedDevices();
                if (mDevices != null & mDevices.size() > 0) {
                    for (BluetoothDevice device : mDevices) {
                        terminateCall(proxy, device);
                        break;
                    }
                } else {
                    if (onCallResultListener != null) {
                        onCallResultListener.onDeviceIsEmpty();
                    }
                }
            }

            @Override
            public void onServiceDisconnected(int profile) {
                if (onCallResultListener != null) {
                    onCallResultListener.onDeviceIsEmpty();
                }
            }
        });
    }


    //挂断电话的实际调用 terminateCall(BluetoothDevice device, BluetoothHeadsetClientCall call)
    private void terminateCall(BluetoothProfile proxy, BluetoothDevice bluetoothDevice) {
        try {
            if (proxy == null || bluetoothDevice == null ) {
                return;
            }

            Class BluetoothHeadsetClient = Class.forName(DIAL_CLASS_NAME);
            Method methodMain = BluetoothHeadsetClient.getMethod(TERMINATE_CALL_METHOD_NAME, BluetoothDevice.class);
            if (methodMain != null) {
                methodMain.invoke(proxy, bluetoothDevice, null);
                //methodMain.invoke(proxy, bluetoothDevice);
            }
        } catch (Exception e) {
            Log.i("yjj", "terminateCall error >>>" + e.toString());
            if (onCallResultListener != null) {
                onCallResultListener.onError(e.getMessage());
            }
        }
    }


/*
    public void terminateCall() {
        try {
            if (mBluetoothProfile == null || mDevice == null ) {
                return;
            }
            Class BluetoothHeadsetClient = Class.forName(DIAL_CLASS_NAME);
            Method methodMain = BluetoothHeadsetClient.getMethod(TERMINATE_CALL_METHOD_NAME, BluetoothDevice.class);
            if (methodMain != null) {
                methodMain.invoke(mBluetoothProfile, mDevice);
            }
        } catch (Exception e) {

        }
    }
*/




    // acceptCall(BluetoothDevice device, int flag)
    private void acceptCall(BluetoothProfile proxy, BluetoothDevice bluetoothDevice) {
        try {
            if (proxy == null || bluetoothDevice == null ) {
                return;
            }
            Class BluetoothHeadsetClient = Class.forName(DIAL_CLASS_NAME);
            //int 对应的class实例为 int.class 或者 Integer.TYPE，但是 Integer 对应的 class 实例为 Integer.class
            Method methodMain = BluetoothHeadsetClient.getMethod(ACCEPT_CALL_METHOD_NAME, BluetoothDevice.class, int.class);
            if (methodMain != null) {
                methodMain.invoke(proxy, bluetoothDevice, 0);
            }
        } catch (Exception e) {
            if (onCallResultListener != null) {
                onCallResultListener.onError(e.getMessage());
            }
        }
    }






    public void acceptCall(final OnCallResultListener onCallResultListener) {

        this.onCallResultListener = onCallResultListener;

        getConnectStatus(new BluetoothProfile.ServiceListener() {
            @Override
            public void onServiceConnected(int profile, BluetoothProfile proxy) {
                mBluetoothProfile = proxy;

                List<BluetoothDevice> mDevices = proxy.getConnectedDevices();
                if (mDevices != null & mDevices.size() > 0) {
                    for (BluetoothDevice device : mDevices) {
                        acceptCall(proxy, device);
                        mDevice = device;
                        break;
                    }
                } else {
                    if (onCallResultListener != null) {
                        onCallResultListener.onDeviceIsEmpty();
                    }
                }
            }

            @Override
            public void onServiceDisconnected(int profile) {
                if (onCallResultListener != null) {
                    onCallResultListener.onDeviceIsEmpty();
                }
            }
        });
    }




    //获取蓝牙的连接状态
    private void getConnectStatus(BluetoothProfile.ServiceListener serviceListener) {
        final int bluetooth_Profile_HEADSET_CLIENT;
        try {
            BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
            if (!adapter.isEnabled()) {
                if (onCallResultListener != null) {
                    onCallResultListener.onBluetoothIsClosed();
                    return;
                }
            }

            bluetooth_Profile_HEADSET_CLIENT = (int) BluetoothProfile.class.getField(BLUE_TOOTH_PROFILE_FIELD).get(null);
            //获取到蓝牙电话的连接状态
            int isConnected = adapter.getProfileConnectionState(bluetooth_Profile_HEADSET_CLIENT);
            if (isConnected == BluetoothProfile.STATE_DISCONNECTED) {
                if (onCallResultListener != null) {
                    onCallResultListener.onDeviceIsEmpty();
                    return;
                }
            }
            adapter.getProfileProxy(App.instance, serviceListener, bluetooth_Profile_HEADSET_CLIENT);

        } catch (Exception e) {
            if (onCallResultListener != null) {
                onCallResultListener.onError(e.getMessage());
            }
        }
    }

    /***
     * 拨号
     * @param proxy
     * @param bluetoothDevice
     * @param number
     */
    private void dial(BluetoothProfile proxy, BluetoothDevice bluetoothDevice, String number) {
        try {
            if (proxy == null || bluetoothDevice == null || (TextUtils.isEmpty(number))) {
                return;
            }
            Class BluetoothHeadsetClient = Class.forName(DIAL_CLASS_NAME);
            Method methodMain = BluetoothHeadsetClient.getMethod(DIAL_METHOD_NAME, BluetoothDevice.class, String.class);
            if (methodMain != null) {
                //蓝牙电话调用的具体执行
                methodMain.invoke(proxy, bluetoothDevice, number);
            }
        } catch (Exception e) {
            if (onCallResultListener != null) {
                onCallResultListener.onError(e.getMessage());
            }
        }


    }





    /*1,根据上一小节的论述,注册BluetoothHeadsetClientCall相关广播,监听来电/接通/对方挂断的状态,获取蓝牙电话的相关信息,比如号码,设备信息等等。
    比如,如果收到来电广播,就可以根据BluetoothHeadsetClientCall获取来电的号码等信息,然后显示来电界面。*/

    /*2,通过BluetoothAdapter 获取并且初始化BluetoothHeadsetClient对象,然后就可以直接调用
    dial()/acceptCall()/rejectCall()/terminateCall() 方法进行拨号/接听/拒接/挂断的操作了。*/

}